package com.macro.mall.tiny.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import sun.util.resources.cldr.aa.CalendarData_aa_DJ;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 *
 * @author kenny
 * @version 1.0
 * @description TODO
 * @date 2023/10/28 12:03
 */
@Component
public class JwtTokenUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;



    /**
     * @description TODO 从token中获取到jwt的负载
     * @param token
     * @return io.jsonwebtoken.Claims
     * @author kenny
     * @date 2023/10/29 10:18
    */
    private Claims getClaimsFromToken(String token){
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败：{}",token);
        }
        return claims;
    }

    /**
     * @description TODO 生成token的过期时间
     *
     * @return java.util.Date
     * @author kenny
     * @date 2023/10/29 10:19
    */
    private Date generateExpirationDate(){
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * @description TODO 从token中获取到用户名
     * @param token
     * @return java.lang.String
     * @author kenny
     * @date 2023/10/29 10:22
    */
    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            username = null;
        }
        return username;
    }

    /**
     * @description TODO 验证token是否还有效
     * @param token
     * @param userDetails
     * @return boolean
     * @author kenny
     * @date 2023/10/29 10:28
    */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * @description TODO 验证token是否已经失效
     * @param token
     * @return boolean
     * @author kenny
     * @date 2023/10/29 10:28
    */
    private boolean isTokenExpired(String token) {
        Date expiredDateFromToken = getExpiredDateFromToken(token);
        return expiredDateFromToken.before(new Date());
    }

    /**
     * @description TODO 从token中获取到过期时间
     * @param token
     * @return java.util.Date
     * @author kenny
     * @date 2023/10/29 10:24
    */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * @description TODO 刷新token
     * @param token
     * @return java.lang.String
     * @author kenny
     * @date 2023/10/29 10:35
    */
    public String refreshToken(String token){
        Claims claims=getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * @description TODO 验证token是否能被刷新
     * @param token
     * @return boolean
     * @author kenny
     * @date 2023/10/29 10:36
    */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * @description TODO 根据用户信息生成token
     * @param userDetails
     * @return java.lang.String
     * @author kenny
     * @date 2023/10/29 10:34
    */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * @description TODO 根据负载生成jwt的token
     * @param claims
     * @return java.lang.String
     * @author kenny
     * @date 2023/10/29 10:33
    */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).setExpiration(generateExpirationDate()).signWith(SignatureAlgorithm.HS512, secret).compact();
    }
}
